export const useFunction = () => {
  function treeifyBin(list: any[], type = "cascader") {
    const nodeMap = new Map<string, any>();
    const roots: any[] = [];

    // 第一遍：初始化所有节点
    list.forEach((item) => {
      let key = item.fdId;
      if (type == "cascader") {
        let it = {
          value: item.fdId,
          label: item.fdName,
        };
        item = it;
      } else if (type == "select") {
        let it = {
          key: item.fdId,
          label: item.fdName,
        };
        item = it;
      }
      nodeMap.set(key, { ...item, children: [] });
    });

    // 第二遍：挂载子节点到父节点
    list.forEach((item) => {
      let node = nodeMap.get(item.fdId);
      if (item.fdParentId && nodeMap.has(item.fdParentId)) {
        // 挂载到父节点
        const parent = nodeMap.get(item.fdParentId);
        parent.children.push(node);
      } else {
        // 根节点
        roots.push(node);
      }
    });

    render(roots);
    console.log(roots);
    return roots;
  }

  let render = (list: any[]) => {
    for (let i = 0; i < list.length; i++) {
      let l = list[i] as any;
      let c = l.children || [];
      if (c.length < 1) {
        delete l["children"];
      } else {
        render(c);
      }
    }
  };

  return {
    treeifyBin,
  };
};
